package se.recept.kollen.module.extension;

import com.google.inject.Injector;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.controller.DefaultObjectFactory;
import net.sourceforge.stripes.controller.ObjectFactory;

/**
 *
 * @author jocke
 */
public class GuiceObjectFactory implements ObjectFactory {

    private static final DefaultObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();

    private Injector injector;

    @Override
    public <T> T newInstance(Class<T> type) {
        try {
            return injector.getInstance(type);
        } catch (com.google.inject.ConfigurationException e) {
            return DEFAULT_OBJECT_FACTORY.newInstance(type);
        }
    }

    @Override
    public <T> T newInstance(Constructor<T> c, Object... os) {
        return DEFAULT_OBJECT_FACTORY.newInstance(c, os);
    }

    @Override
    public <T> T newInstance(Class<T> type, Class<?>[] types, Object[] os) {
        return DEFAULT_OBJECT_FACTORY.newInstance(type, types, os);
    }

    @Override
    public <T> ConstructorWrapper<T> constructor(Class<T> type, Class<?>... types) {
        return DEFAULT_OBJECT_FACTORY.constructor(type, types);
    }

    @Override
    public void init(Configuration c) throws Exception {
        this.injector = (Injector) c.getServletContext().getAttribute(Injector.class.getName());
    }
}
